<template>
  <div class="container">
    <!-- <img src="../assets/static/img/sales.png" alt="" /> -->
    <div class="login-container">
      <div class="login-box row">
        <div class="login-box-left col">
          <div class="login-left column">
            <div
              class="column desc-box"
              v-show="false"
            >
              <div class="logo-name row aic">
                <div class="img mr-1">
                  <img
                    :src="webConfig.loginlogourl"
                    alt
                    srcset
                  />
                </div>
                <h1 class="sys-name">{{ webConfig.SystemName }}</h1>
              </div>

              <h2 class="title">{{ webConfig.SystemName + $language.local("智能交互平台") }}</h2>
              <h2 class="desc">
                <i class="el-icon-caret-right"></i>
                {{ $language.local("更懂企业普惠政策的税大师") }}
                <i class="el-icon-caret-left"></i>
              </h2>
            </div>
          </div>
        </div>
        <div class="login-box-right col">
          <div class="login-box-header">
            <h2 class="login-box-title">
              <span>登录</span>
            </h2>
            <el-form
              :model="loginForm"
              :rules="loginFormRules"
              @submit.native.prevent
              class="login_form"
              ref="loginFormRef"
              status-icon
            >
              <el-form-item prop="userName">
                <xy-input
                  clearable
                  placeholder="请输入用户名"
                  prefix-icon="el-icon-s-custom"
                  v-model="loginForm.userName"
                ></xy-input>
              </el-form-item>
              <el-form-item prop="userPwd">
                <xy-input
                  clearable
                  placeholder="请输入密码"
                  prefix-icon="el-icon-lock"
                  show-password
                  v-model="loginForm.userPwd"
                ></xy-input>
              </el-form-item>
              <el-form-item prop="code">
                <xy-input
                  clearable
                  placeholder="请输入验证码"
                  v-model="loginForm.code"
                >
                  <el-button
                    disabled
                    icon="el-icon-time"
                    slot="append"
                    v-if="timing"
                  >{{ timing }}</el-button>
                  <el-button
                    @click="getVcode('loginFormRef')"
                    icon="el-icon-mobile-phone"
                    slot="append"
                    type="danger"
                    v-else
                  >获取短信验证码</el-button>
                </xy-input>
              </el-form-item>
              <el-form-item>
                <div class="remember">
                  <el-checkbox v-model="remember">{{ $language.local("记住我") }}</el-checkbox>

                  <!-- <el-link :underline="false" href="/">短信验证登录</el-link> -->
                </div>
              </el-form-item>
              <el-form-item class="button_div">
                <!--  -->
                <el-button
                  @click="onSubmit('loginFormRef')"
                  class="login-btn"
                  native-type="submit"
                  size="medium"
                  type="primary"
                >登录</el-button>
              </el-form-item>
              <el-form-item>
                <div class="forget-password">
                  <el-link
                    :underline="false"
                    @click="forgetPassword"
                  >已有账号，忘记密码？</el-link>
                </div>
              </el-form-item>
            </el-form>

            <!-- <p class="pull-right">
            没有帐号？
            <el-link :underline="false" href="/" style="padding-bottom: 2px">
              点此注册
            </el-link>
            </p>-->
          </div>
          <!-- Login form -->
        </div>
      </div>

      <div class="footer">
        CopyRight 2021 All Right Reserved {{ webConfig.SystemName }}
        <a
          href="//beian.miit.gov.cn/"
          target="_blank"
        >{{ webConfig.beian }}</a>
      </div>
    </div>
    <el-dialog
      :visible.sync="forgetPasswordDlgVisivle"
      title="忘记密码"
    >
      <div class="pl-3 pr-3">
        <el-form
          :model="loginForm"
          :rules="$rules"
          class="forget-password"
          ref="forgetFormRef"
        >
          <el-form-item prop="userName">
            <xy-input
              clearable
              placeholder="请输入登陆用户名"
              prefix-icon="el-icon-user"
              v-model="loginForm.userName"
            ></xy-input>
          </el-form-item>
          <el-form-item prop="phone">
            <xy-input
              clearable
              placeholder="请输入开户手机号"
              prefix-icon="el-icon-mobile-phone"
              v-model="loginForm.phone"
            ></xy-input>
          </el-form-item>
          <el-form-item prop="confirmVCode">
            <xy-input
              clearable
              placeholder="请输入短信验证码"
              prefix-icon="el-icon-message"
              v-model="loginForm.confirmVCode"
            >
              <el-button
                disabled
                icon="el-icon-time"
                slot="append"
                v-if="timing"
              >{{ timing }}</el-button>
              <el-button
                @click="getForgetVcode('forgetFormRef')"
                icon="el-icon-mobile-phone"
                slot="append"
                type="danger"
                v-else
              >获取短信验证码</el-button>
            </xy-input>
          </el-form-item>

          <div class="form-footer">
            <el-button
              @click="onForgetLogin('forgetFormRef')"
              class="login-btn"
              size="medium"
              type="primary"
            >确定</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    const validatename = (rule, value, callback) => {
      if ((/^\w+$/).test(value)) {
        callback();
      } else {
        callback(new Error("输入错误！"));
      }
    };
    return {
      webConfig: {
        SystemName: "",
        backgroundImage: "",
        beian: "",
        logo: "",
        loginlogourl: "",
        ico: "",
      },
      verifyCode: null,
      activeName: "first",
      remember: false,
      timing: "",
      loginForm: {
        userName: "",
        userPwd: "",
        code: "",
        confirmVCode: "",
        phone: ""
      },

      enterpriseForm: {
        customTaxIdcd: "",
        vcode: "123456",
      },
      agentForm: {
        idNumber: "",
        vcode: "123456",
      },
      loginFormRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { validator: validatename, trigger: "blur" },
          {
            min: 2,
            message: "长度在 不小于 2 个字符",
            trigger: "blur",
          },
          {
            max: 15,
            message: "长度在 不大于 15 个字符",
            trigger: "blur",
          },
        ],
        userPwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            message: "长度在 不小于 6 个字符",
            trigger: "blur",
          },
          {
            max: 15,
            message: "长度在 不大于 15 个字符",
            trigger: "blur",
          },
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            min: 6,
            message: "长度在 不小于 6 个字符",
            trigger: "blur",
          },
          {
            max: 6,
            message: "长度在 不大于 6 个字符",
            trigger: "blur",
          },
          // { validator: validateVcode, trigger: "blur" },
        ],
      },
      enterpriseFormRules: {
        customTaxIdcd: [
          {
            required: true,
            message: "请输入统一社会信用代码",
            trigger: "blur",
          },
          {
            min: 4,
            message: "长度在 不小于 4 个字符",
            trigger: "blur",
          },
          {
            max: 18,
            message: "长度在 不大于 18 个字符",
            trigger: "blur",
          },
        ],
        vcode: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            min: 6,
            message: "长度在 不小于 6 个字符",
            trigger: "blur",
          },
          {
            max: 6,
            message: "长度在 不大于 6 个字符",
            trigger: "blur",
          },
          // { validator: validateVcode, trigger: "blur" },
        ],
      },
      agentFormRules: {
        idNumber: [
          {
            required: true,
            message: "请输入身份证号或统一信用代码",
            trigger: "blur",
          },
          {
            min: 4,
            message: "长度不小于 4 个字符",
            trigger: "blur",
          },
          {
            max: 40,
            message: "字符超出长度",
            trigger: "blur",
          },
        ],
        vcode: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            min: 6,
            message: "长度不小于 6 个字符",
            trigger: "blur",
          },
          {
            max: 6,
            message: "长度不大于 6 个字符",
            trigger: "blur",
          },
          // { validator: validateVcode, trigger: "blur" },
        ],
      },
      forgetPasswordDlgVisivle: false,
    };
  },
  created() {

    this.getAgentWebConfig();
    let user = this.getUser();
    if (user) {
      user.vcode = "";
      this.loginForm = user;
    }

    let rem = window.localStorage.getItem("remember");
    if (rem) {
      this.remember = true;
    }
  },
  methods: {
    async getAgentWebConfig() {
      let response = await this.$http.get("/api/Login/getAgentWebConfig", {
        // hostname: window.location.hostname,
        // hostname: "www.qijieshuiai.cn",
        hostname: "b.xinyueai.com",
      });
      console.log(response);

      this.webConfig = response.data.Data;
      this.webConfig.backgroundImage = this.webConfig.backgroundImage.slice(3);
      this.webConfig.loginlogourl = this.webConfig.loginlogourl.slice(3);

      this.$store.commit("setData", { webConfig: this.webConfig });
    },
    handleClick() {
      // console.log(tab, event);
    },
    onSubmit(formName) {
      this.$refs[formName].validate(async (valided) => {
        if (!valided) {
          return;
        }

        switch (formName) {
          case "loginFormRef":
            await this.userLogin();

            break;
          case "enterpriseFormRef":
            this.enterpriseLogin();
            break;
          case "agentFormRef":
            this.agentLogin();
            break;
          default:
            break;
        }
      });
    },

    async userLogin() {
      let response = await this.$http.get(
        "/api/Login/UserLogin",
        this.loginForm
      );
      console.log(response);

      const user = response.data.Data;

      let { roletype, musteditpwd, token: headers } = user;

      if (this.loginForm.confirmVCode) {
        musteditpwd = "1";
        this.loginForm.confirmVCode = "";
      }

      this.$http.headers = headers;

      window.sessionStorage.setItem("headers", JSON.stringify(headers));

      window.sessionStorage.setItem("roletype", roletype);
      window.sessionStorage.setItem("musteditpwd", musteditpwd);

      this.setMenuRight(user.roleRight.u_manager_role_values);

      this.$store.commit("login", user);

      console.log(user);

      if (this.remember) {
        this.rememberUser();
        window.localStorage.setItem("remember", 1);
      } else {
        window.localStorage.removeItem("user");
        window.localStorage.removeItem("remember");
      }

      console.log(this.$http.token);
      // const response2 = await this.$http.get("/api/invoice/GetList");
      // console.log(response2);
      this.$message.success("登录成功");
      if (musteditpwd === 1) {
        this.$notify({
          title: "警告",
          message:
            "亲爱的用户您好！为了保护了您的隐私和账户安全，首次登录系统时，请修改您的初始密码！",
          type: "warning",
          duration: 0,
        });
        this.$router.push("/set_pwd");
      } else {
        this.$router.push("/home");
      }
    },
    async enterpriseLogin() {
      try {
        let response = await this.$http.post(
          "/api/MerchantLogin",
          this.enterpriseForm
        );

        if (response.ok) {
          window.sessionStorage.setItem("token", response.data.token);
          this.$message.success("登录成功");
          console.log(response.data);

          this.$store.commit("login", response.data.user);
          if (this.remember) {
            this.rememberUser();
            window.localStorage.setItem("remember", 1);
          } else {
            window.localStorage.removeItem("user");
            window.localStorage.removeItem("remember");
          }

          this.$router.push("/home");
        } else {
          console.log(response);
          this.$message.error("登录失败");
        }
      } catch (error) {
        console.error(error);
        this.$message.error("登录失败");
        return;
      }
    },
    async agentLogin() {
      try {
        let response = await this.$http.post("/api/AgentLogin", this.agentForm);

        if (response.ok) {
          window.sessionStorage.setItem("token", response.data.token);
          this.$message.success("登录成功");
          console.log(response.data);

          this.$store.commit("login", response.data.user);
          if (this.remember) {
            this.rememberUser();
            window.localStorage.setItem("remember", 1);
          } else {
            window.localStorage.removeItem("user");
            window.localStorage.removeItem("remember");
          }

          this.$router.push("/home");
        }
      } catch (error) {
        console.error(error);
        // this.$message.error("登录失败");
      }
    },
    rememberUser() {
      let str = this.encrypted(this.loginForm);
      window.localStorage.setItem("user", str);
    },
    getUser() {
      let str = window.localStorage.getItem("user");
      if (str) {
        let userStr = window.atob(str);
        let user = JSON.parse(userStr);
        return user;
      }
    },
    encrypted(obj) {
      let str = JSON.stringify(obj);
      return window.btoa(str);
    },
    getForgetVcode(formName){
      this.$refs[formName].validateField(["userName", "phone"], (err) => {
        if (err) {
          throw err;
        }
      });
      this.loginForm.confirmVCode = "666888";
    },
    async getVcode(formName) {
      let valided = "";
      this.$refs[formName].validateField(["userName", "userPwd"], (err) => {
        if (valided == "") {
          valided = err;
        }
      });
      if (valided) {
        return;
      }
      let response = await this.$http.get(
        "/api/Login/GetValidateCode",
        this.loginForm
      );
      console.log(response);
      this.verifyCode = response.data.Data.verifyCode;
      this.loginForm.code = response.data.Data.verifyCode;
      let i = 60;
      let timer = setInterval(() => {
        this.timing = i + "s";
        if (i == 0) {
          clearInterval(timer);
          this.timing = null;
        }
        i--;
      }, 1000);
    },
    forgetPassword() {
      this.forgetPasswordDlgVisivle = true;
    },
    async onForgetLogin(formName) {
      console.log(this.loginForm);
      this.loginForm.userName = "qiye";
      await this.$refs[formName].validate();
      // const response = await this.$http.post("api");
      // console.log(response);
      this.forgetPasswordDlgVisivle = false;

      this.userLogin();
    },
    setMenuRight(arr) {
      let obj = {};
      for (let i = 0; i < arr.length; i++) {
        if (!obj[arr[i].nav_name]) {
          obj[arr[i].nav_name] = {};
        }
        obj[arr[i].nav_name][arr[i].action_type] = arr[i].id;
      }
      console.log(obj);
      this.$store.commit("rights", obj);
    },
  },
};
</script>

<style lang="less" scoped>
@media screen and (max-width: 768px) {
  .login-box-left {
    display: none;
  }
}
.container {
  position: relative;
  overflow: hidden;
  .login-container {
    position: absolute;
    top: 50%;
    left: 50%;
    margin: 0 auto;
    padding: 0;
    z-index: 1;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);

    // .bak {
    //   // background: url(../assets/static/img/sales.png) no-repeat;
    //   // background-image: url(../assets/static/img/sales.png);
    //   background-repeat: no-repeat;
    //   background-size: 100% 100%;
    //   background-position: left top;
    //   box-shadow: 0px 20px 80px 0px rgba(0, 0, 0, 0.3);
    //   // width: 64%;
    //   // height: 0;
    //   // padding-top: 36%;
    //   // position: relative;
    // }
    .login-box {
      // background-color: white;

      // height: 0;
      // padding-top: 54%;
      // width: 1040px;
      // height: 585px;
      width: 144vh;
      // max-width: 88vw;
      height: 81vh;
      border-radius: 10px;
      display: flex;
      align-items: stretch;

      background: linear-gradient(0deg, #3a485a 0%, #607089 100%);
      //background: url(../assets/static/img/sales.png) no-repeat;
      background-image: url(../assets/static/img/sales.png);
      background-repeat: no-repeat;
      background-size: 100% 100%;
      background-position: left top;
      box-shadow: 0px 20px 80px 0px rgba(0, 0, 0, 0.3);
      .login-box-left {
        width: 50%;
        flex: 1;
        // align-items: stretch;
        position: relative;
        // background: -webkit-gradient(
        //   linear,
        //   left bottom,
        //   left top,
        //   from(#3a485a),
        //   to(#607089)
        // );
        // background: linear-gradient(0deg, #3a485a 0%, #607089 100%);

        .login-left {
          //min-height: calc(100vh);
          // height: calc(100vh - 100px);
          height: 100%;
          //background: linear-gradient(0deg, #3a485a 0%, #607089 10%);
          color: white;
          border-radius: 5px 0 0 5px;
          padding: 6rem;
          box-sizing: border-box;

          .desc-box {
            position: relative;
            flex-basis: 100%;
            justify-content: center;
            .logo-name {
              position: absolute;
              left: 0;
              top: 0;
              // transform: translate(50%);
              .img {
                width: 38px;
                height: 38px;
                padding: 4px;
                display: flex;
                justify-content: center;
                align-items: center;
                // background: linear-gradient(0deg, #3a485a 0%, #607089 10%);
                background-color: rgba(255, 255, 255, 0.8);
                box-shadow: 0px 10px 10px 0px rgba(0, 0, 0, 0.3);

                border-radius: 50%;
                img {
                  width: 100%;
                  height: auto;
                }
              }
              .sys-name {
                letter-spacing: 5px;
                font-size: 1.6rem;
              }
            }
          }
          .title {
            font-weight: normal;
            letter-spacing: 5px;
            font-size: 2rem;
          }
          .desc {
            font-weight: normal;
            font-size: 1.4rem;
            padding-bottom: 5rem;
          }
          &::after,
          &::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
          }
          &::after {
            background: url(../assets/static/img/loginbak.png) no-repeat right
              bottom;
          }
          &::before {
            background: url(../assets/static/img/loginbefor.png) no-repeat 0 0;
          }
        }
      }
      .login-box-right {
        width: 50%;
        flex: 1;

        border-left: 1px solid #ddd;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: rgba(255, 255, 255, 0.4);
        // overflow: auto;
        box-sizing: border-box;

        .login-box-header {
          width: 72%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          //padding: 3rem;
          .login-box-title {
            width: 100%;
          }
          .login_form {
            width: 100%;
            box-sizing: border-box;

            overflow: hidden;
            .el-form-item {
              .remember {
                display: flex;
                justify-content: space-between;
              }

              .forget-password {
                text-align: center;
              }
            }

            .button_div {
              // display: flex;
              //justify-content: center;
              .login-btn {
                width: 100%;
              }
              // transform: translate(50%);
            }
          }
        }
      }
    }
    .footer {
      // position: fixed;
      // bottom: 0;
      // padding-bottom: 1rem;
      margin-top: 1rem;
      color: #707070;
      font-size: 12px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      .record {
        border-radius: 50%;
      }
    }
  }
  &::before,
  &::after {
    content: "";
    position: fixed;
    bottom: 0;
    background-size: contain;
    background-repeat: no-repeat;
    // z-index: 0;
  }
  &::before {
    width: 197px;
    height: 234px;
    background-image: url(../assets/static/img/bg-left.png);
    left: 0;
  }
  &::after {
    width: 300px;
    height: 250px;
    background-image: url(../assets/static/img/bg-right.png);
    right: 0;
  }
}
</style>
